let util = require('util');
let mysqlPool = require('./MySQLPool');
const field = ["id", "clubId", "setting", "unionId", "unionCoin", "unionState", "ownerUid", "ownerName", "ownerUrl", "clubName", "rel", "gameType", "clubCard", "create_time", "update_time"];
class ClubInfoDao {

    constructor() {
    }

    /**
     * 
     * @param {String} uid 
     * @param {String} clubID 
     */
    async getByClubID(clubID){
        let sql = 'select * from clubinfo where clubId = ? and rel = 0';
        let args = [clubID];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res[0];
        }

        return null;
    }


    async getByName(clubName) {
        let sql = 'select * from clubinfo where clubName = ?'
        let args = [clubName];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res[0];
        }
        return null;
    }


    //add
    async insertErrorInfo(uid,roomid,clubid,gametype,info,ts){
        let sql = 'insert into errorinfo (uid,roomid,clubid,gametype,info,ts,time)' +
            '                       values(?,?,?,?,?,?,now())';
        let args = [uid,roomid,clubid,gametype,info,ts,];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res[0];
        }
        return null;
    }

    //update club set clubName = #{name} where clubId = #{id} and ownerUid = #{uid}
    async updateClubName(clubName,clubId,uid) {
        let sql = 'update club set clubName = ? where clubId = ? and ownerUid = ?'
        let args = [clubName,clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
        return null;
    }

// <update id="updateName">
//         update clubinfo set clubName = #{name} where clubId = #{id} and ownerUid = #{uid}
// </update>

    async updateClubInfoName(clubName,clubId,uid) {
        let sql = 'update clubinfo set clubName = ? where clubId = ? and ownerUid = ?'
        let args = [clubName,clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
        return null;
    }

    async updateSettingByID(setting,clubId,uid) {
        let sql = 'update club set setting = ? where clubId = ? and ownerUid = ?'
        let args = [setting,clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
        return null;
    }

// <update id="updateSettingByID">
//         update clubinfo set setting = #{setting} where clubId = #{id} and ownerUid = #{uid}
// </update>
    async updateInfoSettingByID(setting,clubId,uid) {
        let sql = 'update clubinfo set setting = ? where clubId = ? and ownerUid = ?'
        let args = [setting,clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
        return null;
    }

// <select id="queryMemberUIDByID" resultType="arrays">
//         select memberUid from club where clubId = #{id} group by memberUid
//     </select>

    async queryMemberUIDByID(clubId) {
        let sql = 'select memberUid from club where clubId = ? group by memberUid'
        let args = [clubId];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res[0];
        }
        return null;
    }

// <select id="getByMemberUID" resultType="struct">
//         select * from club where memberUID = #{memberUID} and clubId = #{id} limit 1
//     </select>
    async getByMemberUID(uid,clubId) {
        let sql = 'select * from club where memberUid = ? and clubId = ? limit 1'
        let args = [uid,clubId];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res[0];
        }
        return null;
    }

// <update id="updateStatusByID">
//         update club set agree = #{agree} where id = #{id}
// </update>
    async updateStatusByID(agree,id) {
        let sql = 'update club set agree = ? where id = ?'
        let args = [agree,id];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
        return null;
    }

    async queryMembersByUID2(uid){
        let sql = 'select club.*,clubinfo.clubCard from club inner join clubinfo on club.clubId = clubinfo.clubId  where clubinfo.rel = 0 and club.agree = 1 and club.memberUid = ?';
        let args = [uid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res;
        }
        return null;
    }

    async updateClubMemberByID(clubId,memberUid){
        let sql = 'update club set agree = -3 where clubId = ? and memberUid = ?';
        let args = [clubId,memberUid];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
        return null;
    }


// <update id="updateClubMemberByID">
//         update club set agree = #{agree}
// <if test="agree != nil and agree == 1">
// , join_time = now()
// , joinTick = (unix_timestamp(now()) * 1000)
//         </if>
//     where clubId = #{id} and memberUid = #{memberUID}
// </update>
    async updateClubMemberByIDAgree(memberUid,clubId,agree){
        let sql = 'update club set agree = ? where clubId = ? and memberUid = ?';
        if(agree != null && agree == 1){
            sql = 'update club set agree = ?, join_time = now(), joinTick = (unix_timestamp(now()) * 1000) where clubId = ? and memberUid = ?';
        }
        let args = [agree,clubId,memberUid];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
        return null;
    }

    async queryMembersByID(clubId){
        let sql = 'select a.*, b.name memberNameNew, b.headimgurl memberImgUrlNew from club a left join users b on a.memberUid = b.uid where a.agree = 1 and a.clubId = ?';
        let args = [clubId];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res;
        }
        return null;
    }

    //update club set coins = (coins + #{coins}) where clubId = #{id} and ownerUid = #{uid} and memberUid = #{mUID}
    async addCoinsByMemberUID(coins,clubId,ownerUid,memberUid){
        let sql = 'update club set coins = (coins + ?) where clubId = ? and ownerUid = ? and memberUid = ?';
        let args = [coins,clubId,ownerUid,memberUid];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
        return null;
    }

    //select * from club where ownerUid = #{uid} and clubId = #{clubid} and agree = 0
    async queryApplyMembersByID(ownerUid,clubid){
        let sql = 'select * from club where ownerUid = ? and clubId = ? and agree = 0';
        let args = [ownerUid,clubid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res;
        }
        return null;
    }

    async queryApplyMembers(ownerUid){
        let sql = 'select * from club where ownerUid = ? and agree = 0';
        let args = [ownerUid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res;
        }
        return null;
    }

    //update club set buffer = (buffer + #{buffer}) where clubId = #{id} and ownerUid = #{uid} and memberUid = #{mUID}
    async updateBufferByMemberUID(buffer,clubId,ownerUid,memberUid){
        let sql = 'update club set buffer = (buffer + ?) where clubId = ? and ownerUid = ? and memberUid = ?';
        let args = [buffer,clubId,ownerUid,memberUid];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
        return null;
    }

// <update id="updateBuffer">
//         update users set buffer = (buffer + #{buffer})
//     where uid = #{uid}
//         and (buffer + #{buffer}) >= 0
//         </update>

    async updateBuffer(buffer,uid){
        let sql = 'update users set buffer = (buffer + ?) where uid = ? and (buffer + ?) >= 0';
        let args = [buffer,uid,buffer];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
        return null;
    }

// <select id="getClubMembersCntByID" resultType="value">
//         select count(1) from club where clubId = #{id} and agree = 1
//         </select>

    async getClubMembersCntByID(clubId){
        let sql = 'select count(1) from club where clubId = ? and agree = 1';
        let args = [clubId];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res[0];
        }
        return null;
    }

    /**
     * @param {String} uid
     * @param {String} clubID
     * @param {Number} coins
     */
    async upateCards(clubID, cards){
        let sql = 'update clubinfo set clubCard = (clubCard + ?) where clubId = ?';
        let args = [cards, clubID];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
    
        return 0;
    }

    async saveClubInfoWithTx(clubinfo, conn){
        if(!conn || conn === undefined){
            conn = mysqlPool;
        }
        let sql1 = 'insert into clubinfo (';
        let sql2 = ') values (';
        let sql3 = ')';
        let args = [];
        for(let i = 0; i< field.length; i++){
            let key = field[i];
            if(clubinfo[key] != null && clubinfo[key] !== undefined){
                sql1 = sql1  + field[i] + ", ";
                sql2 = sql2 + "?, "
                args.push(clubinfo[key]);
            }
        }
        sql1 = sql1.substring(0, sql1.length-2);
        sql2 = sql2.substring(0, sql2.length-2);
        let sql = sql1 + sql2 + sql3;
        console.logw(sql, args)
        let res = await conn.query(sql, args);
        if (res){
            return res.insertId;
        }
        return null;
    }

    async judgeClubDissolveAble(clubId, conn){
        if(!conn || conn === undefined){
            conn = mysqlPool;
        }
        //判定俱乐部的疲劳值有没有结清
        let sql = 'select clubId from clubinfo where clubId = ? and unionCoin != 0 and unionCoin is not null';
        let args = [clubId];
        let res = await conn.query(sql, args);
        console.logw(res);
        if(!res || res.length > 0){
            return false;
        }

        //判断俱乐部成员的疲劳值有没有结清
        sql = 'select memberUid from club where clubId = ? and unionCoin != 0 and unionCoin is not null';
        res = await conn.query(sql, args);
        if(!res || res.length > 0){
            return false;
        }

        //判断俱乐部成员的金币豆有没有结清
        sql = 'select memberUid from club where clubId = ? and coins != 0 and coins is not null';
        res = await conn.query(sql, args);
        if(res && res.length === 0){
            return true;
        }

        console.logw(res);
        return false;
    }
    async dissolveClub(clubId, conn){
        if(!conn || conn === undefined){
            conn = mysqlPool;
        }
        let sql = 'update clubinfo set rel = 1, unionCoin = 0, unionId = "", unionState = 1 where clubId = ?';
        let args = [clubId];
        let res = await conn.query(sql, args);
    }

    async updateClubRoyaltySetting(clubId, setting){
        let sql = 'update clubinfo set royaltySetting = ? where clubId = ?';
        let args = [setting, clubId];
        let res = await mysqlPool.query(sql, args);
    }

    async getClubInfo(clubId){
        let sql = 'select * from clubinfo  where clubId = ?';
        let args = [clubId];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0){
            return res[0];
        }
        return null;
    }

    async saveClubRoyaltyRecord(record, conn){
        if(!conn || conn === undefined){
            conn = mysqlPool;
        }
        let sql = 'insert into club_royalty_record (clubId, memberUid, totalAmount, royaltyRate, royaltyAmount, roomId, gameType, state, gameSort,roomTs, createTime) values (?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?)';
        let args = [record.clubId, record.memberUid, record.totalAmount, record.royaltyRate, record.royaltyAmount, record.roomId, record.gameType, 0, record.gameSort,record.roomTs, new Date()];
        let res = await conn.query(sql, args);
        if(res){
            return record;
        }
    }

    async getClubRoyaltyRecordList(startTime, endTime, clubId){
        let sql = 'select a.*, b.name, b.headimgurl from club_royalty_record a left join users b on a.memberUid = b.uid where a.clubId = ? and a.createTime > ? and a.createTime < ?  order by a.createTime desc, a.gameSort';
        let args = [startTime, endTime, clubId];
        return await mysqlPool.query(sql, args);
    }


}

let clubInfoDao = new ClubInfoDao();
module.exports = clubInfoDao;